package com.yanfan.zutai.controller;

import com.alibaba.fastjson2.JSON;
import com.yanfan.common.annotation.Log;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.model.LoginUser;
import com.yanfan.common.core.text.Convert;
import com.yanfan.common.enums.BusinessType;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.common.utils.poi.ExcelUtil;
import com.yanfan.zutai.aop.SysQueryData;
import com.yanfan.zutai.domain.BDeviceManager;
import com.yanfan.zutai.domain.vo.*;
import com.yanfan.zutai.service.IBDeviceManagerService;
import com.yanfan.zutai.util.Detect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * 设备管理Controller
 *
 * @author ruoyi
 * @date 2021-02-27
 */
@RestController
@RequestMapping("/zutai/bDeviceManager")
public class BDeviceManagerController extends BaseController {
    @Autowired
    private IBDeviceManagerService bDeviceManagerService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
//    /**
//     * 查询设备管理列表
//     */
//    //@PreAuthorize("@ss.hasPermi('ghxx:bDeviceManager:list')")
//    @GetMapping("/list")
//    @SysQueryData
//    public TableDataInfo list(BDeviceManager bDeviceManager) {
//        startPage();
//        if(Detect.notEmpty(bDeviceManager.getQueryDeptId())){
//            bDeviceManager.setDeptIdStrs(bDeviceManager.getQueryDeptId());
//        }
//        List<BDeviceManager> list = bDeviceManagerService.selectBDeviceManagerList(bDeviceManager);
//        return getDataTable(list);
//    }

    /**
     * 导出设备管理列表
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bDeviceManager:export')")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @SysQueryData
    public void export(HttpServletResponse response, BDeviceManager bDeviceManager) {
        List<BDeviceManager> list = bDeviceManagerService.selectBDeviceManagerList(bDeviceManager);
        ExcelUtil<BDeviceManager> util = new ExcelUtil<BDeviceManager>(BDeviceManager.class);
        util.exportExcel(response, list, "设备");
    }

    /**
     * 获取设备管理详细信息
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bDeviceManager:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        BDeviceManager bDeviceManager = bDeviceManagerService.selectBDeviceManagerById(id);
        return AjaxResult.success(bDeviceManager);
    }

//    /**
//     * 新增设备管理
//     */
//    //@PreAuthorize("@ss.hasPermi('ghxx:bDeviceManager:add')")
//    @Log(title = "设备管理", businessType = BusinessType.INSERT)
//    @PostMapping
//    @SysInitData
//    public AjaxResult add(@RequestBody BDeviceManager bDeviceManager) {
//        bDeviceManager.setDeviceStatus(0);
//        if (Detect.isEmpty(bDeviceManager.getDeviceMac())) {
//            return AjaxResult.error("无设备号，添加失败");
//        } else if (bDeviceManager.getDeviceMac().length() != 15) {
//            return AjaxResult.error("设备号格式错误，添加失败");
//        } else {
//            Integer count = jdbcTemplate.queryForObject("select count(1) from B_Device_Manager where device_mac=?  ", Integer.class, bDeviceManager.getDeviceMac());
//            if (count > 0) {
//                return AjaxResult.error("设备已存在，添加失败");
//            }
//        }
//        bDeviceManagerService.insertBDeviceManager(bDeviceManager);
//        return AjaxResult.success(bDeviceManager);
//    }

    /**
     * 修改设备管理
     */
//    //@PreAuthorize("@ss.hasPermi('ghxx:bDeviceManager:edit')")
//    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
//    @PutMapping
//    @RepeatSubmit(interval = 1000, message = "修改设备管理")
//    public AjaxResult edit(@RequestBody BDeviceManager bDeviceManager) {
//        if (Detect.isEmpty(bDeviceManager.getDeviceMac())) {
//            return AjaxResult.error("无设备号，修改失败");
//        } else if (bDeviceManager.getDeviceMac().length() != 15) {
//            return AjaxResult.error("设备号格式错误，修改失败");
//        } else {
//            Integer count = jdbcTemplate.queryForObject("select count(1) from B_Device_Manager where device_mac=? and id !=? ", Integer.class, bDeviceManager.getDeviceMac(), bDeviceManager.getId());
//            if (count > 0) {
//                return AjaxResult.error("设备已存在，修改失败");
//            }
//        }
//        String sql="update b_device_real_data set device_name=?  where device_imei=? ";
//        jdbcTemplate.update(sql,bDeviceManager.getDeviceName(),bDeviceManager.getDeviceMac());
//        sql="update b_device_zt set device_name=?  where device_mac=? ";
//        jdbcTemplate.update(sql,bDeviceManager.getDeviceName(),bDeviceManager.getDeviceMac());
//        return toAjax(bDeviceManagerService.updateBDeviceManager(bDeviceManager));
//    }

    /**
     * 删除设备管理
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bDeviceManager:remove')")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            BDeviceManager bDeviceManager = bDeviceManagerService.selectBDeviceManagerById(ids[i]);
            bDeviceManagerService.deleteDevice(bDeviceManager);
        }
        return toAjax(bDeviceManagerService.deleteBDeviceManagerByIds(ids));
    }

    /**
     * 设备excel导入
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bDeviceManager:importData')")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<DeviceExcelVo> util = new ExcelUtil<DeviceExcelVo>(DeviceExcelVo.class);
        List<DeviceExcelVo> deviceList = util.importExcel(file.getInputStream());
        String message = bDeviceManagerService.importData(deviceList);
        return AjaxResult.success(message);
    }

    /**
     * 设备excel导入模板下载
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bDeviceManager:importTemplate')")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<DeviceExcelVo> util = new ExcelUtil<DeviceExcelVo>(DeviceExcelVo.class);
        return util.importTemplateExcel("设备数据");
    }

    /**
     * 首页设备总览
     */
    @GetMapping("/getDeviceOverview")
    @SysQueryData
    public AjaxResult getDeviceOverview(BDeviceManager bDeviceManager) throws Exception {
        BDeviceMonitorVo monitor = bDeviceManagerService.getDeviceOverview(bDeviceManager);
        return AjaxResult.success(monitor);
    }


    /**
     * 查询模拟量折线图
     */
    @GetMapping("/getEcharts")
    @SysQueryData
    public AjaxResult getEcharts(BDeviceManager bDeviceManager) {
        BDeviceEcharts echarts = bDeviceManagerService.getEcharts(bDeviceManager);
        return AjaxResult.success(echarts);
    }

    /**
     * 查询设备在线情况
     */
    @GetMapping("/getDeviceStatus")
    public Boolean getDeviceStatus(BDeviceManager bDeviceManager) {
        return bDeviceManagerService.selectBDeviceManagerOnlineByImei(bDeviceManager.getDeviceMac());
    }

    /**
     * 导出设备管理及其管理表
     */
    @GetMapping("/exportDevice")
    public AjaxResult exportDevice(BDeviceManagerJson bDeviceManager) {
        BDeviceManager deviceManager = bDeviceManagerService.exportDevice(bDeviceManager);
        return AjaxResult.success(deviceManager);
    }

    /**
     * 复制设备管理及其管理表
     */
    @PostMapping("/copyDevice")
    @Transactional
    public AjaxResult copyDevice(@RequestBody BDeviceManagerJson bDeviceManager) {
        if (Detect.isEmpty(bDeviceManager.getDeviceMacNew()) || Detect.isEmpty(bDeviceManager.getDeviceMac())) {
            return AjaxResult.error("参数不符合规定");
        }
        Integer count = jdbcTemplate.queryForObject("select count(1) from B_Device_Manager where device_mac=?  ", Integer.class, bDeviceManager.getDeviceMacNew());
        if (count > 0) {
            return AjaxResult.error("设备已存在，复制失败");
        }
        bDeviceManagerService.copyDevice(bDeviceManager);
        return AjaxResult.success();
    }

    /**
     * 导入设备管理及其管理表
     */
    @PostMapping("/importDevice")
    @Transactional
    public AjaxResult importDevice(@RequestBody MultipartFile file, BDeviceManagerJson bDeviceManager) throws Exception {
        if (Detect.isEmpty(bDeviceManager.getDeviceMacNew())) {
            return AjaxResult.error("参数不符合规定");
        }
        Integer count = jdbcTemplate.queryForObject("select count(1) from B_Device_Manager where device_mac=?  ", Integer.class, bDeviceManager.getDeviceMacNew());
        if (count > 0) {
            return AjaxResult.error("设备已存在，导入失败");
        }
        if (file.isEmpty()) {
            return AjaxResult.error("无效的配置文件");
        }
        if (file.getOriginalFilename().indexOf("json") == -1) {
            return AjaxResult.error("无效的配置文件");
        }
        InputStream inputStream = file.getInputStream();
        BDeviceManagerJson bDeviceManagerJsonNew = new BDeviceManagerJson();
        try {
            bDeviceManagerJsonNew = JSON.parseObject(inputStream, BDeviceManagerJson.class);
        } catch (Exception e) {
            return AjaxResult.error("无效的配置文件");
        } finally {
            inputStream.close();
        }
        if (Detect.isEmpty(bDeviceManagerJsonNew.getDeviceMac())) {
            return AjaxResult.error("无效的配置文件");
        }
        bDeviceManager.setDeviceMac(bDeviceManagerJsonNew.getDeviceMac());
        bDeviceManagerService.copyDevice(bDeviceManager);
        return AjaxResult.success("导入成功");
    }
    /**
     * 获取省市区
     */
    @GetMapping("/getArea")
    public AjaxResult getArea(BArea bArea){
        if(bArea.getLvl()==1){
            String sql="SELECT DISTINCT provinceZh from city where countryZh='中国'";
            BeanPropertyRowMapper<BArea> bDeviceMaintainRowMapper = new BeanPropertyRowMapper<>(BArea.class);
            List<BArea> bAreaList = jdbcTemplate.query(sql, bDeviceMaintainRowMapper);
            return AjaxResult.success(bAreaList);
        }else if(bArea.getLvl()==2){
            String sql="SELECT  DISTINCT leaderZh from city where provinceZh=? ";
            BeanPropertyRowMapper<BArea> bDeviceMaintainRowMapper = new BeanPropertyRowMapper<>(BArea.class);
            List<BArea> bAreaList = jdbcTemplate.query(sql, bDeviceMaintainRowMapper,bArea.getProvinceZh());
            return AjaxResult.success(bAreaList);
        }else{
            String sql=" SELECT * from city where leaderZh=?";
            BeanPropertyRowMapper<BArea> bDeviceMaintainRowMapper = new BeanPropertyRowMapper<>(BArea.class);
            List<BArea> bAreaList = jdbcTemplate.query(sql, bDeviceMaintainRowMapper,bArea.getLeaderZh());
            return AjaxResult.success(bAreaList);
        }
    }

    /**
     * 授权设备
     */
    @PostMapping(value = "/empowerDevice")
    public AjaxResult empowerDevice(@RequestBody BDeviceEmpower bDeviceEmpower) {
        BDeviceManager bDeviceManager = bDeviceManagerService.selectBDeviceManagerById(Convert.toLong(bDeviceEmpower.getDeviceId()));
        if (bDeviceEmpower.getEmpowerType().equals("设备授权")) {
            if (bDeviceManager.getDeptIdStrs().indexOf(bDeviceEmpower.getDeptId()) == -1) {
                bDeviceManager.setDeptIdStrs(bDeviceManager.getDeptIdStrs() + bDeviceEmpower.getDeptId() + ",");
                bDeviceManagerService.updateBDeviceManager(bDeviceManager);
            }
        } else {
            bDeviceManager.setDeptIdStrs(bDeviceManager.getDeptIdStrs().replace(bDeviceEmpower.getDeptId() + ",", ""));
            bDeviceManagerService.updateBDeviceManager(bDeviceManager);
        }
        return AjaxResult.success();
    }

    /**
     * 小程序查询设备概况
     */
    @GetMapping("/getDeviceOverviewWeChat")
    public AjaxResult getDeviceOverviewWeChat(BDeviceManager bDeviceManager) throws Exception {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        bDeviceManager.setDeptIdStrs("%," + loginUser.getUser().getDept().getDeptId() + ",%");
        BDeviceMonitorVo monitor = bDeviceManagerService.getDeviceOverviewWeChat(bDeviceManager);
        return AjaxResult.success(monitor);
    }

    /**
     *组态-统计图形-饼形图调用接口
     */
    @GetMapping("/getDevice")
    public AjaxResult getDevice(BDeviceManager bDeviceManager){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        BDeviceMonitorVo monitor = bDeviceManagerService.getDevice(bDeviceManager);
        return AjaxResult.success(monitor);
    }

    /**
     * 查询设备变量统计
     */
    @GetMapping("/getDeviceStatistic")
    public AjaxResult getDeviceStatistic(BDeviceStatistic bDeviceStatistic) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        bDeviceStatistic.setDeptIdStrs("%," + loginUser.getUser().getDept().getDeptId() + ",%");
        bDeviceStatistic = bDeviceManagerService.getDeviceStatistic(bDeviceStatistic);
        return AjaxResult.success(bDeviceStatistic);
    }

    /**
     * 微信弹窗
     */
    @Log(title = "微信弹窗", businessType = BusinessType.INSERT)
    @PostMapping(value = "/weChatAdd")
    public AjaxResult weChatAdd() {
        return AjaxResult.success("用户点击了");
    }
}
